import U from "./U.js";
import fs from "fs"
import MingSerialPort from "./MingSerialPort.js"
const sp= new MingSerialPort("COM3")

const CON_BUFFER_LEN=1024;
let t1=new Date().getTime()
async function main(){
    let prebuf = fs.readFileSync("D:\\workspace\\test\\MODMAN_RTX_108\\vs\\purepcmodbus\\1.bin");
    //不是128的倍数就补0
    var rbuf = new Buffer(prebuf.length+(CON_BUFFER_LEN-prebuf.length%CON_BUFFER_LEN)) ;
    prebuf.copy(rbuf) ;
    const packageLeng=Number.parseInt(rbuf.length/CON_BUFFER_LEN) ;
    let startAddress=0;
    for (let i=0;i<packageLeng;i++) {
        startAddress = i * CON_BUFFER_LEN;
        let rlist = rbuf.slice(startAddress, startAddress + CON_BUFFER_LEN);
        let calcCrc= U.crc16xmodem( rlist)
        let hi=calcCrc>>8 & 0xff;
        let li=calcCrc & 0xff;
        let packNum=i+1;
        rlist=[0x01,packNum,255-packNum,...rlist,hi,li];
        let r= await sp.send( rlist);
        if(r[0]==6){
            console.log("success "+i);
            continue;
        }else if(r[0]==0x15 ){
            i--;
            continue
        }else if(r[0]==0x43){
            i=-1;
            continue
        }else{
            i--;
            continue
            console.log("fail "+JSON.stringify(r));
        }
        break
    }
    let r= await sp.send( [0x04]);
    console.log("over .....")
    console.log(packageLeng)
    let t2=new Date().getTime()

    console.log(t2-t1+"ms")

}

main()